package org.goodsmanager.controller;

import jakarta.validation.Valid;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.goodsmanager.common.Result;
import org.goodsmanager.entity.Category;
import org.goodsmanager.entity.Product;
import org.goodsmanager.service.CategoryService;
import org.goodsmanager.service.ProductService;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.*;
import java.util.List;
import java.util.Map;

/**
 * 商品Controller
 *
 * @author Goods Manager System
 * @version 1.0.0
 */
@Slf4j
@Controller
@RequestMapping("/product")
@RequiredArgsConstructor
public class ProductController {

    private final ProductService productService;
    private final CategoryService categoryService;

    /**
     * 商品列表页面
     */
    @GetMapping("/list")
    public String listPage(Model model,
                           @RequestParam(defaultValue = "1") int page,
                           @RequestParam(defaultValue = "10") int size,
                           @RequestParam(required = false) String keyword,
                           @RequestParam(required = false) String categoryId,
                           @RequestParam(required = false) Integer status,
                           @RequestParam(defaultValue = "created_at") String sortBy,
                           @RequestParam(defaultValue = "DESC") String sortOrder) {
        try {
            // 查询商品列表
            Map<String, Object> pageData = productService.getProductsByPage(
                    page, size, keyword, categoryId, status, null, null, sortBy, sortOrder);

            // 查询分类列表
            List<Category> categories = categoryService.getAllCategories();

            model.addAttribute("pageData", pageData);
            model.addAttribute("categories", categories);
            model.addAttribute("keyword", keyword);
            model.addAttribute("categoryId", categoryId);
            model.addAttribute("status", status);
            model.addAttribute("sortBy", sortBy);
            model.addAttribute("sortOrder", sortOrder);

            return "product/list";
        } catch (Exception e) {
            log.error("查询商品列表失败", e);
            model.addAttribute("error", "查询商品列表失败: " + e.getMessage());
            return "error";
        }
    }

    /**
     * 跳转到新增商品页面
     */
    @GetMapping("/add")
    public String addPage(Model model) {
        try {
            List<Category> categories = categoryService.getAllCategories();
            model.addAttribute("categories", categories);
            model.addAttribute("product", new Product());
            return "product/form";
        } catch (Exception e) {
            log.error("跳转新增页面失败", e);
            model.addAttribute("error", "跳转新增页面失败: " + e.getMessage());
            return "error";
        }
    }

    /**
     * 跳转到编辑商品页面
     */
    @GetMapping("/edit/{id}")
    public String editPage(@PathVariable String id, Model model) {
        try {
            Product product = productService.getProductById(id);
            if (product == null) {
                model.addAttribute("error", "商品不存在");
                return "error";
            }

            List<Category> categories = categoryService.getAllCategories();
            model.addAttribute("product", product);
            model.addAttribute("categories", categories);
            return "product/form";
        } catch (Exception e) {
            log.error("跳转编辑页面失败", e);
            model.addAttribute("error", "跳转编辑页面失败: " + e.getMessage());
            return "error";
        }
    }

    /**
     * 商品详情页面
     */
    @GetMapping("/detail/{id}")
    public String detailPage(@PathVariable String id, Model model) {
        try {
            Product product = productService.getProductById(id);
            if (product == null) {
                model.addAttribute("error", "商品不存在");
                return "error";
            }
            model.addAttribute("product", product);
            return "product/detail";
        } catch (Exception e) {
            log.error("查询商品详情失败", e);
            model.addAttribute("error", "查询商品详情失败: " + e.getMessage());
            return "error";
        }
    }

    /**
     * 保存商品（新增或更新）
     */
    @PostMapping("/save")
    @ResponseBody
    public Result<String> saveProduct(@Valid @RequestBody Product product, BindingResult bindingResult) {
        try {
            // 数据验证
            if (bindingResult.hasErrors()) {
                String errorMsg = bindingResult.getFieldError().getDefaultMessage();
                return Result.error(400, errorMsg);
            }

            boolean success;
            if (product.getId() == null || product.getId().isEmpty()) {
                // 新增
                success = productService.addProduct(product);
                if (success) {
                    return Result.success("新增商品成功", product.getId());
                } else {
                    return Result.error("新增商品失败，商品编码可能已存在");
                }
            } else {
                // 更新
                success = productService.updateProduct(product);
                if (success) {
                    return Result.success("更新商品成功", product.getId());
                } else {
                    return Result.error("更新商品失败，商品编码可能已被使用");
                }
            }
        } catch (Exception e) {
            log.error("保存商品失败", e);
            return Result.error("保存商品失败: " + e.getMessage());
        }
    }

    /**
     * 删除商品
     */
    @DeleteMapping("/delete/{id}")
    @ResponseBody
    public Result<String> deleteProduct(@PathVariable String id) {
        try {
            boolean success = productService.deleteProduct(id);
            if (success) {
                return Result.success("删除商品成功");
            } else {
                return Result.error("删除商品失败");
            }
        } catch (Exception e) {
            log.error("删除商品失败", e);
            return Result.error("删除商品失败: " + e.getMessage());
        }
    }

    /**
     * 批量删除商品
     */
    @DeleteMapping("/batchDelete")
    @ResponseBody
    public Result<String> batchDeleteProducts(@RequestBody List<String> ids) {
        try {
            boolean success = productService.batchDeleteProducts(ids);
            if (success) {
                return Result.success("批量删除成功，删除数量: " + ids.size());
            } else {
                return Result.error("批量删除失败");
            }
        } catch (Exception e) {
            log.error("批量删除商品失败", e);
            return Result.error("批量删除失败: " + e.getMessage());
        }
    }

    /**
     * 批量更新状态
     */
    @PutMapping("/batchUpdateStatus")
    @ResponseBody
    public Result<String> batchUpdateStatus(@RequestBody Map<String, Object> params) {
        try {
            @SuppressWarnings("unchecked")
            List<String> ids = (List<String>) params.get("ids");
            Integer status = (Integer) params.get("status");

            boolean success = productService.batchUpdateStatus(ids, status);
            if (success) {
                return Result.success("批量更新状态成功");
            } else {
                return Result.error("批量更新状态失败");
            }
        } catch (Exception e) {
            log.error("批量更新状态失败", e);
            return Result.error("批量更新状态失败: " + e.getMessage());
        }
    }

    /**
     * 更新库存
     */
    @PutMapping("/updateStock")
    @ResponseBody
    public Result<String> updateStock(@RequestBody Map<String, Object> params) {
        try {
            String id = (String) params.get("id");
            Integer quantity = (Integer) params.get("quantity");

            boolean success = productService.updateStock(id, quantity);
            if (success) {
                return Result.success("更新库存成功");
            } else {
                return Result.error("更新库存失败");
            }
        } catch (Exception e) {
            log.error("更新库存失败", e);
            return Result.error("更新库存失败: " + e.getMessage());
        }
    }

    /**
     * 根据ID查询商品
     */
    @GetMapping("/get/{id}")
    @ResponseBody
    public Result<Product> getProduct(@PathVariable String id) {
        try {
            Product product = productService.getProductById(id);
            if (product != null) {
                return Result.success(product);
            } else {
                return Result.error("商品不存在");
            }
        } catch (Exception e) {
            log.error("查询商品失败", e);
            return Result.error("查询商品失败: " + e.getMessage());
        }
    }

    /**
     * 搜索商品
     */
    @GetMapping("/search")
    @ResponseBody
    public Result<Map<String, Object>> searchProducts(
            @RequestParam String keyword,
            @RequestParam(defaultValue = "1") int page,
            @RequestParam(defaultValue = "10") int size) {
        try {
            Map<String, Object> result = productService.searchProducts(keyword, page, size);
            return Result.success(result);
        } catch (Exception e) {
            log.error("搜索商品失败", e);
            return Result.error("搜索商品失败: " + e.getMessage());
        }
    }

    /**
     * 获取热销商品
     */
    @GetMapping("/hot")
    @ResponseBody
    public Result<List<Product>> getHotProducts(@RequestParam(defaultValue = "10") int limit) {
        try {
            List<Product> products = productService.getHotProducts(limit);
            return Result.success(products);
        } catch (Exception e) {
            log.error("查询热销商品失败", e);
            return Result.error("查询热销商品失败: " + e.getMessage());
        }
    }

    /**
     * 获取新品商品
     */
    @GetMapping("/new")
    @ResponseBody
    public Result<List<Product>> getNewProducts(@RequestParam(defaultValue = "10") int limit) {
        try {
            List<Product> products = productService.getNewProducts(limit);
            return Result.success(products);
        } catch (Exception e) {
            log.error("查询新品商品失败", e);
            return Result.error("查询新品商品失败: " + e.getMessage());
        }
    }

    /**
     * 获取库存预警商品
     */
    @GetMapping("/lowStock")
    @ResponseBody
    public Result<List<Product>> getLowStockProducts() {
        try {
            List<Product> products = productService.getLowStockProducts();
            return Result.success(products);
        } catch (Exception e) {
            log.error("查询库存预警商品失败", e);
            return Result.error("查询库存预警商品失败: " + e.getMessage());
        }
    }
}